from rest_framework.decorators import api_view
from rest_framework.response import Response
from django.http import HttpResponse
from rest_framework.views import APIView
from rest_framework.viewsets import ModelViewSet,GenericViewSet
from rest_framework.generics import GenericAPIView, ListAPIView,CreateAPIView,UpdateAPIView
from rest_framework import authentication, permissions
from django.contrib.auth import get_user_model
from rest_framework.throttling import UserRateThrottle
from .models import Book
from rest_framework import serializers

User = get_user_model()


@api_view(['GET', "POST"])
def test1(request):
    #session
    user = request.user


    if request.method == 'post':
        pass
    if request.method == 'get':
        pass
    if not user:
        return Response('delay')
    return Response({"test": 'hello world'})


def django_test1(request):
    import json

    return HttpResponse({"test": 'hello world'})


class OncePerDayUserThrottle(UserRateThrottle):
    rate = '10/minute'


class Test3V2(APIView):
    """
    权限控制 速度控制 用户识别

    接口要求: 需要我们返回所有的用户信息
             授权用户才能去查看这个敏感数据
    """
    # 权限接口 是去认证用户
    authentication_classes = (authentication.TokenAuthentication,authentication.SessionAuthentication)
    permission_classes = (permissions.IsAuthenticatedOrReadOnly,)
    throttle_classes = (OncePerDayUserThrottle,)

    # 限速
    def get(self, request):
        data = Book.objects.all()

        datas = []

        for i in data:
            tmp_data = {'name': i.name, 'add_time': i.add_time}
            datas.append(tmp_data)

        return Response(datas)

    def post(self, request):
        data = request.POST
        res = Book.objects.create(**data)

        return Response({"id": res.id, "name": res.name, 'add_time': res.add_time})


class Test4(GenericAPIView):
    """
    权限控制 速度控制 用户识别

    接口要求: 需要我们返回所有的用户信息
             授权用户才能去查看这个敏感数据
    """
    # 权限接口 是去认证用户
    authentication_classes = (authentication.TokenAuthentication,authentication.SessionAuthentication)
    permission_classes = (permissions.IsAdminUser,)
    throttle_classes = (OncePerDayUserThrottle,)

    # 限速
    def get(self, request):
        data = Book.objects.all()

        datas = []

        for i in data:
            tmp_data = {'name': i.name, 'add_time': i.add_time}
            datas.append(tmp_data)

        return Response(datas)

    def post(self, request):
        data = request.POST
        res = Book.objects.create(**data)

        return Response({"id": res.id, "name": res.name, 'add_time': res.add_time})


class BookListSerializer(serializers.Serializer):
    name = serializers.CharField(max_length=20)
    add_time = serializers.DateTimeField()



from rest_framework import mixins
from rest_framework.mixins import CreateModelMixin,ListModelMixin,RetrieveModelMixin,DestroyModelMixin,UpdateModelMixin


# class BookListViewSet(ListAPIView):
#     # select * from book
#     queryset = Book.objects.all()
#     serializer_class = BookListSerializer

# data = Book.objects.all()
class TestList(object):

    def get(self, request, *args, **kwargs):
        return Response('fuck you')

# class BookListViewSet(mixins.ListModelMixin,mixins.CreateModelMixin,
#                   GenericAPIView
#     ):
#     # select * from book
#     queryset = Book.objects.all()
#     serializer_class = BookListSerializer
#
#     def get(self, request, *args, **kwargs):
#         return self.list(request, *args, **kwargs)
#
#     def post(self, request, *args, **kwargs):
#         return self.create(request, *args, **kwargs)

class BookListV2ViewSet(mixins.DestroyModelMixin,mixins.ListModelMixin,mixins.UpdateModelMixin,mixins.RetrieveModelMixin,GenericViewSet):
    queryset = Book.objects.all()
    serializer_class = BookListSerializer

    def get_queryset(self):

        method = self.request.method

        x = self.action
        return Book.objects.all()


"""
实现一个方法:放里面有书,
1.随便哪个用户可以去创建一本书
2.只有创建这本书的用户可以去修改这本书
3.只有创建这本书的用户可以去删除这本书
4.所有用户可以看到所有的书
"""
class BookSerializer(serializers.ModelSerializer):


    class Meta:
        model = Book
        fields = "__all__"

    def create(self, validated_data):
        validated_data['creator'] = self.context['request']._user
        validated_data['name'] = '不好意思'

        return super().create(validated_data)


    def update(self, instance, validated_data):

        if self.context['request']._user != instance.creator:
            raise serializers.ValidationError('不是创建者')
        return super().update(instance,validated_data)












class BookViewSet(mixins.DestroyModelMixin,mixins.ListModelMixin,CreateModelMixin,mixins.UpdateModelMixin,GenericViewSet):


    queryset = Book.objects.all()
    serializer_class = BookSerializer

    # def perform_destroy(self, instance):
    #     user = self.request.user
    #
    #     if user != instance.creator:
    #         raise serializers.ValidationError('没有权限删除')
    #     instance.delete()

    def perform_create(self, serializer):
        serializer.save()

    def perform_destroy(self, instance):

        if self.request._user != instance.creator:
            raise serializers.ValidationError('不能删除')
        return super().perform_destroy(instance)










